package com.gjs.gateway;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

@Configuration
public class GatewayCorsFilter  {

    @Bean
    public CorsWebFilter corsWebFilter(){
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 1、配置跨域
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.setAllowCredentials(true);
        // 2、设置哪些路径需要跨域
        source.registerCorsConfiguration("/**",corsConfiguration);

        return new CorsWebFilter(source);
    }

    // 该方法是通过实现WebFilter中的filter方法实现的，但通过测试上面的方法更方便，所以改用上面的方法
//    @Override
//    public Mono<Void> filter(ServerWebExchange ctx, WebFilterChain chain) {
//        ServerHttpRequest request = ctx.getRequest();
//        if (CorsUtils.isCorsRequest(request)) {
//            ServerHttpResponse response = ctx.getResponse();
//            HttpHeaders headers = response.getHeaders();
//            headers.remove(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN);
//            headers.set(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "http://127.0.0.1:9529");
//            headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
//            headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "Content-Type,token,Accept,Accept-Language,Content-Language");
//            if (request.getMethod() == HttpMethod.OPTIONS) {
//                response.setStatusCode(HttpStatus.OK);
//                return Mono.empty();
//            }
//        }
//        return chain.filter(ctx);
//    }
}
